package com.mobilepay.moneypig.base;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.githang.statusbar.StatusBarCompat;
import com.mobilepay.moneypig.R;
import com.mobilepay.moneypig.model.application.App;
import com.mobilepay.moneypig.utils.FragmentManager;
import com.mobilepay.moneypig.utils.SysUtil;
import com.mobilepay.moneypig.utils.inject.InjectUtil;
import com.mobilepay.moneypig.view.CustomProgressDialog;
import com.mobilepay.moneypig.view.statuslayout.StatusLayoutManager;
import com.umeng.analytics.MobclickAgent;

/**
 * Created by xlm on 2017/7/12 0012
 */

public abstract class BaseActivity extends AppCompatActivity implements View.OnClickListener {
    private BaseActivity mThis;
    private FragmentManager mFragmentManager;
    private BaseFragment mCurrentFragment;
    public StatusLayoutManager statusLayoutManager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        onGetIntent(getIntent());
        super.onCreate(savedInstanceState);
        //设置状态栏颜色
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            StatusBarCompat.setStatusBarColor(this, Color.parseColor("#e46641"));
        }
        mThis = this;
        if (mThis != null) {
            //添加activity到stack中
            App.getApp().addActivity(mThis);
        }

        beforeSetContentView();
        onSetContentView();
        afterSetContentView();

        onFindView();
        initViews();

        beforeOnCreate(savedInstanceState);
        afterOnCreate(savedInstanceState);

        onSetListener();
    }

    /**
     * 直接跳转
     *
     * @param cls
     */
    public void startActivity(Class<?> cls) {
        Intent intent = new Intent(this, cls);
        startActivity(intent);
        finish();
    }

    /**
     * @param cls
     * @param finish 是否finish
     * @param delay  是否延迟
     */
    public void startActivity(Class<?> cls, boolean finish, boolean delay) {
        final Intent intent = new Intent(this, cls);
        if (finish) {
            if (delay) {
                new Handler(getMainLooper()).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        startActivity(intent);
                        finish();
                    }
                }, SHOW_TIME_MIN + 10);
            } else {
                startActivity(intent);
                finish();
            }
        } else {
            if (delay) {
                new Handler(getMainLooper()).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        startActivity(intent);
                    }
                }, SHOW_TIME_MIN + 10);
            } else {
                startActivity(intent);
            }
        }
    }

    /**
     * 延迟finish
     *
     * @param delay
     */
    public void finishActivity(boolean delay) {
        if (delay) {
            new Handler(getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    finish();
                }
            }, SHOW_TIME_MIN + 10);
        } else {
            finish();
        }
    }

    /**
     * @param delay
     * @param times
     */
    public void finishActivityMillions(boolean delay, long times) {
        if (delay) {
            new Handler(getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    finish();
                }
            }, times + 10);
        } else {
            finish();
        }
    }

    /**
     * 延迟跳转
     *
     * @param intent
     * @param delay
     */
    public void startActivity(final Intent intent, boolean delay) {
        if (delay) {
            new Handler(getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    startActivity(intent);
                }
            }, SHOW_TIME_MIN);
        } else {
            startActivity(intent);
        }
    }


    /**
     * 点击
     *
     * @param v
     */
    @Override
    public void onClick(View v) {

    }

    /**
     * 设置是否重写Activity载入退出动画
     *
     * @param override
     */
    private boolean overridePending = false;

    public void setOverridePending(boolean override) {
        overridePending = override;
    }

    private boolean isFirst = true;

    @Override
    protected void onResume() {
        if (!overridePending) {
            if (isFirst) {
                overridePendingTransition(R.anim.in_activity_rtl, R.anim.out_activity_ltr);
            } else {
                overridePendingTransition(R.anim.in_back_activity_rtl, R.anim.out_back_activity_ltr);
            }
            isFirst = false;
        }
        //umeng统计
        MobclickAgent.onResume(this);
        super.onResume();
    }

    /**
     * 加载fragment
     *
     * @param framlayout
     * @return
     */
    public FragmentManager initFragmentManager(int framlayout) {
        mFragmentManager = new FragmentManager(getThis(), framlayout);
        return mFragmentManager;
    }

    public void setCurrentFragment(BaseFragment fragment) {
        mCurrentFragment = fragment;
    }

    public BaseFragment getCurrentFragment() {
        return mCurrentFragment;
    }

    @Override
    public void onBackPressed() {
        if (mCurrentFragment != null) {
            mCurrentFragment.onBackPressed();
            return;
        }
        afterBackPressed();
    }

    protected void afterBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void finish() {
        beforeFinish();
        super.finish();
    }

    protected void beforeFinish() {

    }

    @Override
    protected void onDestroy() {
        if (mThis != null) {
            App.getApp().removeActivity(mThis);
        }
        super.onDestroy();
    }


    protected void onGetIntent(Intent intent) {

    }

    /**
     * 通过注解自动绑定资源ID
     */
    private void injectView() {
        InjectUtil.injectActivityFields(this, false);
    }

    protected void beforeSetContentView() {

    }

    protected void afterSetContentView() {

    }

    protected void onFindView() {

    }

    protected void beforeOnCreate(Bundle savedInstanceState) {
    }

    public void hideSoftInput() {
        View view = getCurrentFocus();
        if (view != null) {
            SysUtil.hideSoftInput(view);
        }
    }

    public BaseActivity getThis() {
        return mThis;
    }

    private Toast mToast;

    /**
     * Toast展示
     *
     * @param msg
     */
    public void showToastShort(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mToast != null) {
                    mToast.cancel();
                    mToast = null;
                }
                View layout = getLayoutInflater().inflate(R.layout.toast_custom, (ViewGroup) findViewById(R.id.rl_toast));
                TextView text = (TextView) layout.findViewById(R.id.toast_content);
                text.setText(msg);
                mToast = new Toast(getThis());
                mToast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 240);
                mToast.setDuration(Toast.LENGTH_SHORT);
                mToast.setView(layout);
                mToast.show();
            }
        });
    }

    public void showToastLong(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mToast != null) {
                    mToast.cancel();
                    mToast = null;
                }
                View layout = getLayoutInflater().inflate(R.layout.toast_custom, (ViewGroup) findViewById(R.id.rl_toast));
                TextView text = (TextView) layout.findViewById(R.id.toast_content);
                text.setText(msg);
                mToast = new Toast(getThis());
                mToast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 240);
                mToast.setDuration(Toast.LENGTH_SHORT);
                mToast.setView(layout);
                mToast.show();
            }
        });
    }


    @Override
    protected void onPause() {
        destroyDialogOrToast();
        MobclickAgent.onPause(this);
        super.onPause();
    }

    /**
     * 界面销毁取消toast和Dialog
     */
    private void destroyDialogOrToast() {
        if (mToast != null) {
            mToast.cancel();
        }
        if (mCustomProgressDialog != null && mCustomProgressDialog.isShowing()) {
            mCustomProgressDialog.dismiss();
        }
    }

    private ProgressDialog mProgressDialog;
    private CustomProgressDialog mCustomProgressDialog;

    /**
     * 创建加载dialog
     */

    public CustomProgressDialog getDlProgressDialog(String msg) {
        if (mCustomProgressDialog == null) {
            mCustomProgressDialog = new CustomProgressDialog(BaseActivity.this);
        }
        mCustomProgressDialog.setMessage(msg);
        return mCustomProgressDialog;
    }

    private static final int SHOW_TIME_MIN = 600;
    long startTime;
    long loadingTime;

    /**
     * 展示加载dialog
     *
     * @param msg
     */
    public void showProgress(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    startTime = System.currentTimeMillis();
                    getDlProgressDialog(msg).show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 延迟取消加载dialog
     */
    public void dismissProgress() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (mCustomProgressDialog != null && mCustomProgressDialog.isShowing()) {
                        loadingTime = System.currentTimeMillis() - startTime;
                        if (loadingTime < SHOW_TIME_MIN) {
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    mCustomProgressDialog.dismiss();
                                }
                            }, SHOW_TIME_MIN - loadingTime);
                        } else
                            mCustomProgressDialog.dismiss();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 加载dialog
     *
     * @param msg
     * @return
     */
    public ProgressDialog getProgressDialog(String msg) {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(BaseActivity.this);
        }
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.setCancelable(true);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setMessage(msg);
        return mProgressDialog;
    }

    /**
     * 下载进度dialog
     *
     * @param msg
     */
    public void showDownProgress(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    getProgressDialog(msg).show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 取消下载dialog
     */
    public void dismissDownProgress() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (mProgressDialog != null && mProgressDialog.isShowing()) {
                        mProgressDialog.dismiss();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 检查内存卡权限
     *
     * @param request_code
     * @return
     */
    public boolean checkStoragePermission(int request_code) {
        int permissionr = 0;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
            permissionr = ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        int permissionw = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permissionr == PackageManager.PERMISSION_GRANTED && permissionw == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            String[] PERMISSIONS_STORAGE = new String[0];
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                PERMISSIONS_STORAGE = new String[]{
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                };
            }
            ActivityCompat.requestPermissions(getThis(), PERMISSIONS_STORAGE,
                    request_code);
            return false;
        }
    }

    /**
     * 摄像头
     *
     * @param request_code
     * @return
     */
    public boolean checkCameraPermission(int request_code) {
        int permission = ActivityCompat.checkSelfPermission(getThis(), Manifest.permission.CAMERA);
        if (permission == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            String[] PERMISSIONS_STORAGE = {
                    Manifest.permission.CAMERA
            };
            ActivityCompat.requestPermissions(getThis(), PERMISSIONS_STORAGE,
                    request_code);
            return false;
        }
    }

    /**
     * 录音
     *
     * @param request_code
     * @return
     */
    public boolean checkRecordAudioPermission(int request_code) {
        int permission = ActivityCompat.checkSelfPermission(getThis(), Manifest.permission.RECORD_AUDIO);
        if (permission == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            String[] PERMISSIONS_STORAGE = {
                    Manifest.permission.RECORD_AUDIO
            };
            ActivityCompat.requestPermissions(getThis(), PERMISSIONS_STORAGE,
                    request_code);
            return false;
        }
    }

    /**
     * 地图定位
     *
     * @param request_code
     * @return
     */
    public boolean checkLocationPermission(int request_code) {
        int permissionf = ActivityCompat.checkSelfPermission(getThis(), Manifest.permission.ACCESS_FINE_LOCATION);
        int permissionc = ActivityCompat.checkSelfPermission(getThis(), Manifest.permission.ACCESS_COARSE_LOCATION);
        if (permissionf == PackageManager.PERMISSION_GRANTED && permissionc == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            String[] PERMISSIONS_STORAGE = {
                    Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION
            };
            ActivityCompat.requestPermissions(getThis(), PERMISSIONS_STORAGE,
                    request_code);
            return false;
        }
    }

    /**
     * 通讯录权限
     *
     * @param request_code
     * @return
     */
    public boolean checkReadPhoneStatePermission(int request_code) {
        int permissionf = ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
        if (permissionf == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_PHONE_STATE};
            ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE,
                    request_code);
            return false;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (permissions[0]) {
            case Manifest.permission.READ_EXTERNAL_STORAGE:
            case Manifest.permission.WRITE_EXTERNAL_STORAGE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    onStoragePermission(requestCode, true);
                } else {
                    onStoragePermission(requestCode, false);
                }
                break;
            case Manifest.permission.CAMERA:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    onCameraPermission(requestCode, true);
                } else {
                    onCameraPermission(requestCode, false);
                }
                break;
            case Manifest.permission.RECORD_AUDIO:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    onRecordAudioPermission(requestCode, true);
                } else {
                    onRecordAudioPermission(requestCode, false);
                }
                break;
            case Manifest.permission.ACCESS_FINE_LOCATION:
            case Manifest.permission.ACCESS_COARSE_LOCATION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    onLocationPermission(requestCode, true);
                } else {
                    onLocationPermission(requestCode, false);
                }
                break;
            case Manifest.permission.READ_PHONE_STATE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    onReadPhoneStatePermission(requestCode, true);
                } else {
                    onReadPhoneStatePermission(requestCode, false);
                }
                break;
        }
    }

    public void onStoragePermission(int result_code, boolean result) {

    }

    public void onCameraPermission(int result_code, boolean result) {

    }

    public void onRecordAudioPermission(int result_code, boolean result) {

    }

    public void onLocationPermission(int result_code, boolean result) {

    }

    public void onReadPhoneStatePermission(int result_code, boolean result) {

    }

    protected abstract void onSetContentView();//初始化布局文件

    protected abstract void initViews();//绑定view

    protected abstract void afterOnCreate(Bundle savedInstanceState);//事件操作

    protected abstract void onSetListener();//设置监听

    private void initBaseView() {
        LinearLayout ll_main = (LinearLayout) findViewById(R.id.ll_main);
        ll_main.addView(statusLayoutManager.getRootLayout());
    }

    public void initStatusLayout() {
//        statusLayoutManager = StatusLayoutManager.newBuilder(this)
////                .contentView(R.layout.activity_content_data)
//                .emptyDataView(R.layout.activity_empty_data)
////                .netWorkErrorView(R.layout.activity_networkerror)
//                .onRetryListener(new OnRetryListener() {
//                    @Override
//                    public void onRetry() {
//                        //为重试加载按钮的监听事件
//                    }
//                })
//                .onShowHideViewListener(new OnShowHideViewListener() {
//                    @Override
//                    public void onShowView(View view, int id) {
//                        //为状态View显示监听事件
//                    }
//
//                    @Override
//                    public void onHideView(View view, int id) {
//                        //为状态View隐藏监听事件
//                    }
//                })
//                .build();
    }

    //显示内容
    protected void showContent() {
        statusLayoutManager.showContent();
    }

    //显示没有数据
    protected void showEmptyData() {
        statusLayoutManager.showEmptyData();
    }

    //显示加载错误
    protected void showError() {
        statusLayoutManager.showError();
    }

    //显示没有网络
    protected void showNetWorkError() {
        statusLayoutManager.showNetWorkError();
    }

    //显示加载中
    protected void showLoading() {
        statusLayoutManager.showLoading();
    }
}
